import { getProvinceDataApi } from "@/api/global";
import { defineStore } from "pinia";

export const useGlobalStore = defineStore('global', {
    state: () => {
        return {
            provinceData: []
        }
    },
    actions: {
        async initProvinceData() {
            if (this.provinceData.length === 0) {
                try {
                    const results = await getProvinceDataApi();
                    this.provinceData = results.filter(item => item.level === 1 && item.parentid === 0).map(item => {
                        return {
                            name: item.name,
                            cities: results.filter(child => child.parentid === item.id && child.level === 2).map(child => {
                                return {
                                    name: child.name,
                                    districts: results.filter(third => third.parentid === child.id && third.level === 3).map(third => {
                                        return third.name
                                    })
                                }
                            })
                        };
                    });
                } catch (error) {
                    console.error('getProvince error', error);
                }
            }
        },

        setProvinceData(data) {
            this.provinceData = data;
        }
    },
    persist: {
        enabled: false
    }
});